<template>
	<view class="w-table">
		<uni-collapse ref="collapse" v-model="opened" @change="resize">
			<uni-collapse-item :ref="`tableRow${i}`" :show-animation="true" class="w-table-row" v-for="(row, i) in _value" :key="`row_${i}`">
				<template v-slot:title>
					<view class="w-table-row-tt">
						<view style="display: flex; flex: 1; align-items: center;">
							<text style="padding: 8px 15px;">{{ $t('webAuto.details') }} {{i+1}}</text>
							<uni-icons v-if="errRow.has(i)" type="info" :size="20" color="#CE5266"></uni-icons>
						</view>
						<view @click.stop="delTbRow(i)" style="color: #999999;" v-if="!readonly">{{$t('webAuto.delete')}}</view>
					</view>

				</template>
				<uni-forms :ref="`wflowTableForm_${i}`" :rules="rules" :modelValue="_value[i]" label-position="top"
					label-width="200">
					<uni-forms-item class="w-form-item" v-show="showItem(col, _value[i][col.id])" v-for="col in formProps.columns" :name="col.id" :key="col.id"
						:required="col.props.required">
						<template v-slot:label>
							<view class="titles">
								<text style="color: #CE5266;" v-if="col.props.required">* </text>
								<text >{{$t(col.title)}}</text>
							</view>
						</template>
						<w-form-item @resize="$refs.collapse.resize()" :type="col.name" v-model="_value[i][col.id]" :form-props="col.props"
							:readonly="col.perm !== 'E'" :formData="formData" :index="i+ 1" />
					</uni-forms-item>
				</uni-forms>
			</uni-collapse-item>
		</uni-collapse>
		<view class="w-table-add" @click="addRow" v-if="!readonly">+ {{$t('webAuto.AddDetails')}}</view>
	</view>
</template>

<script>
	import { showItem } from '@/utils/tool.js'
	export default {
		name: 'TableList',
		inject: ['validFuncs'],
		props: {
			id: String,
			modelValue: { //表单双向绑定的值
				type: Array,
				default: () => {
					return []
				}
			},
			formData: { //表单值
				type: Object,
				default: () => {
					return {}
				}
			},
			formProps: { //表单联动相关配置
				type: Object,
				default: () => {
					return {}
				}
			},
			readonly: Boolean,

		},
		computed: {
			_value: {
				get() {
					return this.modelValue
				},
				set(val) {
					this.$emit('update:modelValue', val)
				}
			},
			rules() {
				const formRule = {}
				this.formProps.columns.forEach(v => {
					formRule[v.id] = {
						rules: [{
							required: v.props.required,
							errorMessage: this.$t('webAuto.enterContent') + v.title
						}]
					}
				})
				return formRule
			}
		},
		data() {
			return {
				opened: ['0'],
				errRow: new Set()
			}
		},
		beforeMount() {
			this.validFuncs[this.id] = (rule, value, data, callback) => {
				return new Promise((resolve, reject) => {
					this.validate(isOk => {
						if(isOk) resolve()
						else reject(new Error(this.$t('webAuto.CheckContent')))
					})
				})
			}
			if(!this._value){
				this._value = []
			}
		},
		onUnload() {
			uni.$off('resize')
		},
		mounted() {
			this.$nextTick(() => {
				this.$refs.collapse.resize()
				uni.$emit('showFp')
			})
			uni.$on('resize', () => {
				setTimeout(() => this.$refs.collapse?.resize(), 800)
			})
		},
		methods: {
			showItem,
			resize(){
				setTimeout(() => this.$emit('resize'), 800)
			},
			validate(call) {
				console.log('表格校验')
				//校验表格所有行数据
				const valids = []
				if (this._value.length == 0) {
				Promise.all(valids).then((results) => {
					call(true)
				})
			} else {
				this._value.forEach((v, i) => {
					valids.push(new Promise((resolve) => {
						//对表格数据进行循环校验
						const formRef = this.$refs[`wflowTableForm_${this._value.length - 1}`]
						formRef[0].validate().then(res => {
							this.errRow.delete(i)
							resolve(true)
						}).catch(err => {
							//展开所有错误的行
							if (this.opened.indexOf(i) < 0) {
								this.opened.push(i)
							}
							this.errRow.add(i)
							resolve(false)
						})
					}))
				})
				if (valids.length > 0) {
					Promise.all(valids).then((results) => {
						// 检查结果所有校验都成功为true
						const isSuccess = results.every((valid) => valid === true);
						call(isSuccess)
					})
				}
			}
			},
			addRow() {
				if ((this._value || []).length > 0) {
					const formRef = this.$refs[`wflowTableForm_${this._value.length - 1}`]
					//校验上一行表单
					this.validate(valid => {
						if (valid) {
							this.doAddRow()
						} else {
							uni.showToast({
								icon: 'none',
								title: this.$t('webAuto.CompleteData')
							})
						}
					})
				} else {
					this.doAddRow()
				}
			},
			delTbRow(i) {
				uni.showModal({
					title: this.$t('webAuto.prompt'),
					content: this.$t('webAuto.DeleteData'),
					success: (res) => {
						if (res.confirm) {
							this._value.splice(i, 1)
							this._value = this._value
							setTimeout(() => uni.$emit('showFp'), 500)
						}
					}
				});
			},
			doAddRow() {
				if ((this.formProps.maxSize || 0) > 0 && this.formProps.columns.length >= this.formProps.maxSize) {
					uni.showToast({
						icon: 'none',
						title: this.$t('webAuto.limit')
					})
					return
				}
				const row = {}
				this.formProps.columns.forEach(v => row[v.id] = null)
				this._value.push(row)
				this._value = this._value
				this.resize()
				this.$forceUpdate()
				setTimeout(() => uni.$emit('showFp'), 500)
			}
		},
		watch: {
			opened: {
				deep: true,
				handler() {
					setTimeout(() => uni.$emit('showFp'), 500)
				}
			}
		},
		emits: ['update:modelValue', 'resize']
	}
</script>

<style lang="less" scoped>
	.w-table {
		//background-color: #F4F5F7;
	}

	.w-table-add {
		// display: flex;
		// justify-content: center;
		// align-items: center;
		color: #4478F7;
		padding: 20rpx 0 ;
		text-align: center;

	}

	:deep(.w-table-row) {
		border: 0.5rpx solid #CCC;
		.w-table-row-tt {
			display: flex;
			align-items: center;
			
			&>view:first-child {
				flex: 1;
			}
			
			&>view:last-child {
				
			}
		}
		
		.uni-forms-item__error {
			padding-top: 0;
		}
		
		.uni-collapse-item__title-box {
			height: 35px;
			line-height: 35px;
			background-color: #f8f9fa;
		}

		.uni-collapse-item__title {
			border-bottom: 2px solid white;
			background-color: #f8f9fa;
			border-radius: 5px;

			.uni-collapse-item__title-wrap {
				display: flex;
				align-items: center;
				margin-right: 10px;
			}
		}

		.uni-collapse-item__wrap-content.uni-collapse-item--border {
			border-bottom-color: white;
		}

		.w-form-item {
			border-bottom: 2px solid #F8F9FA;
			margin-bottom: 0;
			display: flex;
			flex-direction: row;
			padding: 0 0 0.2rem 0 !important;
		}
		.w-form-item2 {
			border-bottom: 2px solid #F8F9FA;
			margin-bottom: 0;
			display: flex;
			flex-direction: row;
			padding: 0  !important;
		}

		.w-form-item:last-child {
			border-bottom: none;
		}
	}
	.titles{
		width: 3.5rem;
		display: flex;
		align-items: center;
		text-align: right;
		padding-right: 0.40625rem;
		font-size: 0.75rem !important;
		justify-content: right;
		white-space: pre-wrap;
		line-height: 40rpx;
		color: #848484;
	}
</style>